var options_key = "RUYI_BROWSER_OPTIONS"; //配置数据存储key
var search_suggent = {};    //关键词与搜索建议对应关系

//获取当前配置信息
chrome.storage.local.get(options_key,function(data){
    if(data[options_key]){
        var config_data = data[options_key]['site_nav'];
        for(var i=0;i<config_data.length;i++){
            var classify = config_data[i];
            search_suggent[classify.name] = classify.site;
            search_suggent[classify.keyword] = classify.site;
        }
    }
});

// 获取当前选项卡ID
function getCurrentTabId(callback){
	chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
		if(callback) callback(tabs.length ? tabs[0].id: null);
	});
}

// 当前标签打开某个链接
function openUrlCurrentTab(url){
	getCurrentTabId(function(tabId){
		chrome.tabs.update(tabId, {url: url});
	})
}

//自定义快捷搜索结果
chrome.omnibox.onInputChanged.addListener(function(text,suggent){
    if(!text) return;
    if(typeof(search_suggent[text])!=typeof([])) return;
    var suggent_site = [];
    for(var i=0;i<search_suggent[text].length;i++){
        var site_name = search_suggent[text][i].name;
        var site_url = search_suggent[text][i].url;
        suggent_site.push({"content":site_url,"description":site_name});
    }
    suggent(suggent_site);
});

// 当用户接收关键字建议时触发
chrome.omnibox.onInputEntered.addListener(function(text){
    if(!text) return;
    var lowerText = text.toLowerCase();
    if(lowerText.startsWith('http://')||lowerText.startsWith('https://')){
        openUrlCurrentTab(text);
    }
});

// 拦截页面请求
chrome.storage.local.get(options_key,function(data){
    if(data[options_key]){
        var block_url_list = data[options_key]['block_url'];
        if(block_url_list && block_url_list.length){
            chrome.webRequest.onBeforeRequest.addListener(function(request){
                console.log("Block request: "+request.url);
                return {"cancel":true}
            },{urls:block_url_list},["blocking"]);
        }
    }
});